<?php
//用户管理
namespace app\admin\controller;
use \think\Request;
use app\common\model\User as UserModel;
use app\common\model\Area as AreaModel;
use app\common\model\DogFamily as DogFamilyModel;
use  app\common\model\Dog as DogModel;
use app\common\model\Proposer as ProposerModel;
use app\common\model\Integral as IntegralModel;
use think\Db;
class  User extends \app\admin\controller\Base {
    protected $res = array(
        'index'   => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'statistics'   => array('css' => '2,3,4', 'js' => 'echart,My97DatePicker'),
        'loss'   => array('css' => '2,3,4', 'js' => 'echart,My97DatePicker'),
        'integral'  => array('css' => '2,3,4', 'js' => 'echart,My97DatePicker')
    );

    /**
     * @return mixed
     * 用户列表首页
     */
    public function index(){
        $UserModel = new UserModel();
        $AreaModel = new AreaModel();
        $search = input('get.search/a');
        $page = input('get.page');
        $search = $this->search($search, $page);
        $list = $UserModel->relData(15,$search);
        $action = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $wherePro['level'] = 1;
        if($search[4]!=''){
            $whereCity['pid'] = $search[4];
        }else{
            $whereCity['pid'] = 2;
        }
        if($search[5]!=''){
            $whereDistrict['pid'] = $search[5];

        }else{
            $whereDistrict['pid'] = 52;
        }
        $province =$AreaModel->selectArea($wherePro);
        $city =$AreaModel->selectArea($whereCity);
        $district =$AreaModel->selectArea($whereDistrict);
        $this->assign(
            array(
                'status'=>$UserModel::$user_status,
                'sex'=>$UserModel::$sex,
                'user_attestation'=>$UserModel::$user_attestation,
                'action'=>$action,
                'list'=>$list,
                'page'=>$page,
                'search' => $search,
                'province' => $province,
                'city' => $city,
                'district' => $district,
            )
        );
        return $this->fetch();
    }

    /**
     * @return \think\response\Json
     * 修改用户状态
     */
    public function UpdateUser(){
        $ids = strtoarray(input('post.ids'));
        $act = input('post.act');
        $aModel = new UserModel;
        foreach ($ids as $key => $value) {
            $data = array(
                'user_id'     => $value,
                'user_status' => $act,
            );
            $result = $aModel->update($data);
        }
        if ($result) {
            return $this->api_success('操作成功');
        } else {
            return $this->api_dbError();
        }
    }

    /***
     * @return \think\response\Json
     * 删除用户
     */
    public function DelUser()
    {
        $ids = strtoarray(input('post.ids'));
        $aModel = new UserModel;
        $where['user_id'] = array('In', $ids);
        $result = $aModel->where($where)->delete();
        if ($result) {
            return $this->api_success('操作成功');
        } else {
            return $this->api_dbError();
        }
    }

    /**
     * @return mixed
     * 编辑页面
     */
    public function save(){
        $id = input('get.id');
        $UserModel = new UserModel();
        $where['user_id'] = $id;
        $field = 'user_id,user_username';
        $list = $UserModel->getUserOne($where,$field);
        $this->assign('list',$list);
        return $this->fetch();
    }

    /***
     * @return \think\response\Json
     * 编辑功能
     */
    public function saveInfo(){
        if(Request::instance()->isPost()){
            $id = input('post.id');
            $user_username = input('post.user_username');
            $data['user_id'] = $id;
            $data['user_username'] = $user_username;
            $UserModel = new UserModel();
            $list = $UserModel->update($data);
            if($list){
                return $this->api_success();
            }else{
                return $this->api_dbError();
            }
        }else{
            return $this->api_dbError();
        }
    }

    /**
     * 审核页面
     */
    public function examine(){
        $UserModel = new UserModel();
        $id = input('get.id');
        $where['user_id'] = $id;
        $field = 'user_rel_name,user_facade_img,user_ldentity_img,user_hand_img,user_card,user_id,user_attestation';
        $list = $UserModel->getUserOne($where,$field);
        if($list['user_attestation']==3){
            $this->assign('ad',$list);
            return $this->fetch();
        }else{
            $this->redirect('user/index');
        }
    }
    
    /**
     * @return mixed
     */
    public function audit(){
        $id = input('id');
        if(!$id){
            return $this->api_dbError();
        }
        $data = Db::table('up_u_user')
            ->alias('uuu')
            ->join('up_admin ua', 'ua.id = uuu.admin_id','left')
            ->field('uuu.user_rel_name,uuu.user_facade_img,uuu.user_ldentity_img,uuu.user_hand_img,uuu.user_card,uuu.user_reason,uuu.user_attestation,ua.nickname')
            ->where('user_id', $id)
            ->find();
        if(!$data){
            return $this->api_dbError();
        }
        $this->assign(array(
            'data' => $data
        ));
        return $this->fetch();
    }

    /***
     * @return \think\response\Json
     * 审核功能
     */
    public function examineInfo(){
        $UserModel = new UserModel();
        $id = input('post.id');
        $user_attestation = Db::table('up_u_user')->where('user_id',$id)->value('user_attestation');
        $user_integral = Db::table('up_u_user')->where('user_id',$id)->value('user_integral');
        $user_phone = Db::table('up_u_user')->where('user_id',$id)->value('user_phone');
        if($user_attestation==2){
            return $this->api_dbError("已经实名认证完成，不能重复认证");
        }

        $status = input('post.status');
        $reason = input('post.reason');
        $data['user_id'] = $id;
        $data['user_attestation'] = $status;
        $data['user_authentication_time'] = date('Y-m-d H:i:s',time());
        if($status==4){
            $data['user_reason'] = $reason;
        }
        if($status==4){
            $this->Jpush($id,'您的实名认证审核没有通过',1,array('type'=>1));
            $this->sendCode($user_phone,296123);
        }
        if($status==2){
            $array['integral_status'] =2;
            $array['integral_user_id'] =$id;
            $array['integral_num'] =10;
            $array['integral_time'] = date('Y-m-d H:i:s',time());

            Db::table('up_integral')->insert($array);

            $this->Jpush($id,'恭喜您的实名认证审核通过',1,array('type'=>1));
            $this->sendCode($user_phone,296122);
            $admin_id = session('admin')['id'];
            $user_integral = $user_integral+10;
            Db::table('up_u_user')
                ->where('user_id',$id)
                ->update([
                    'user_integral'=>$user_integral,
                    'admin_id'=>$admin_id
                    ]);
        }
        $res = $UserModel->update($data);
        if($res){
            return $this->api_success();
        }else{
            return $this->api_dbError();
        }
    }
    /**
     * 用户积分列表
     */
    public function integral(){
        $IntegralModel = new IntegralModel();
        $search = input('param.search/a');
//        $page = input('param.page');
        $user_id = input('param.user_id');
        $list = $IntegralModel->userIntegral($search, 15, $user_id);
        $this->assign(
            array(
                'list'               =>        $list,
                'integral_status'    =>        $IntegralModel::$integral_status,
                'search'             =>        $search,
                'user_id'            =>        $user_id
            )
        );
        return $this->fetch();
    }

    /**
     * 查询市
     */
    public function city(){
        $city = $_POST['city'];
        $cityArray = Db::table('up_area')->where('pid',$city)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }
    /**
     * 查询区
     */
    public function area(){
        $area = $_POST['area'];
        $cityArray = Db::table('up_area')->where('pid',$area)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }

    /**
     * @return \think\response\Json
     * 认证用户导出
     */
    public function excelDownload(){
        $UserModel = new UserModel();
        $DogFamilyModel = new DogFamilyModel();
        $DogModel = new DogModel();
        $ProposerModel = new ProposerModel();
        $search = input('post.search/a');

        $res = $UserModel->excelData($search);

        $result = array();
        foreach ($res as $key=>$vo){
            $result[$key]['user_id'] = $vo['user_id'];

            $result[$key]['user_username'] = $vo['user_username'];
//            $result[$key]['user_rel_name'] = $vo['user_rel_name'];
            if($vo['user_gender']==1){
                $result[$key]['user_gender'] = '男';
            }else{
                $result[$key]['user_gender'] = '女';
            }
//            if($vo['user_card']!=''){
//                $result[$key]['user_age'] = $this->getAgeByID($vo['user_card']);
//                $result[$key]['address'] = $this->userCard(substr($vo['user_card'],0,2));
//
//            }else{
//                $result[$key]['user_age'] = '';
//                $result[$key]['address'] ='';
//            }
            //设备
            if($vo['equipment']!=''){
                $result[$key]['equipment'] =$vo['equipment'];
            }else{
                $result[$key]['equipment'] ='';
            }
            $result[$key]['user_address'] = $vo['province'].$vo['city'].$vo['district'];
            $user_time = strtotime($vo['user_time']);
            $result[$key]['user_time'] = date('Y',$user_time).'/'.date('m',$user_time).'/'.date('d',$user_time);//注册日期
//            $user_authentication_time = strtotime($vo['user_authentication_time']);
//            $result[$key]['user_authentication_time'] = date('Y',$user_authentication_time).'/'.date('m',$user_authentication_time).'/'.date('d',$user_authentication_time);//注册日期;

//            $result[$key]['user_integral'] = $vo['user_integral'];

            $whereDog['user_id'] = $vo['user_id'];
            $result[$key]['register_dog_num'] = $DogFamilyModel->countNum($whereDog);//登记狗狗数量

            $whereStray['user_id'] = $vo['user_id'];
            $whereStray['dog_type'] = 1;
            $whereStray['dog_preserve'] = 2;
            $result[$key]['stray_dog_num'] = $DogModel->countNum($whereStray)?$DogModel->countNum($whereStray):0;//发布流浪狗表单数量

            $whereMutual['user_id'] = $vo['user_id'];
            $whereMutual['dog_type'] = 2;
            $whereMutual['dog_preserve'] = 2;
            $result[$key]['mutual_dog_num'] = $DogModel->countNum($whereStray)?$DogModel->countNum($whereStray):0;//发布互助表单数量

            $whereAdopt['user_id'] = $vo['user_id'];
            $whereAdopt['dog_type'] = 3;
            $whereAdopt['dog_preserve'] = 2;
            $result[$key]['adopt_dog_num'] = $DogModel->countNum($whereStray)?$DogModel->countNum($whereStray):0;//发布领养表单数量

            $whereSubmit['proposer_user_id'] = $vo['user_id'];
            $result[$key]['submit_dog_num'] = $ProposerModel->countNum($whereSubmit)?$ProposerModel->countNum($whereSubmit):0;//提交领养表单数量

            $whereFind['user_id'] = $vo['user_id'];
            $whereFind['dog_type'] = 4;
            $whereFind['dog_preserve'] = 2;
            $result[$key]['find_dog_num'] = $DogModel->countNum($whereStray)?$DogModel->countNum($whereStray):0;
        }
        $xlsCell  = array(
            array('user_id','用户ID'),
            array('user_username','用户名'),
//            array('user_rel_name','姓名'),
            array('user_gender','性别'),
//            array('user_age','年龄'),
//            array('address','户口所在地'),
            array('equipment','设备'),

            array('user_address','注册地'),
            array('user_time','注册日期'),
//            array('user_authentication_time','认证日期'),
//            array('user_integral','爱心积分'),
            array('register_dog_num','登记狗狗数量'),
            array('stray_dog_num','发布流浪狗表单数量'),
            array('mutual_dog_num','发布互助表单数量'),
            array('adopt_dog_num','发布领养表单数量'),
            array('submit_dog_num','提交领养表单数量'),
            array('find_dog_num','发布寻狗启事表单数量'),
        );
        $data = $this->exportExcel($xlsCell,$result);
        return $data;
    }

    /**
     * @return mixed
     * 用户折线列表
     */
    public function statistics(){
        $AreaModel = new AreaModel();
        $search = input('post.search/a');
        $page = input('post.page');
        $search = $this->search($search, $page);
        $action = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $wherePro['level'] = 1;
        if($search[4]!=''){
            $whereCity['pid'] = $search[4];
        }else{
            $whereCity['pid'] = 2;
        }
        if($search[5]!=''){
            $whereDistrict['pid'] = $search[5];
        }else{
            $whereDistrict['pid'] = 52;
        }
        $province =$AreaModel->selectArea($wherePro);
        $city =$AreaModel->selectArea($whereCity);
        $district =$AreaModel->selectArea($whereDistrict);
        $this->assign(
            array(
                'action'=>$action,
                'page'=>$page,
                'search' => $search,
                'province' => $province,
                'city' => $city,
                'district' => $district,
            )
        );
        return $this->fetch();
    }

    /***
     * @return \think\response\Json
     * 柱状图统计
     */
    public function echartsColumn(){
        $result = $res = array();
        $UserModel = new UserModel();
        $search = input('post.search/a');
        if($search[3]!=''&&$search[4]!=''){
            $date_time = $this->prDates($search[3],$search[4],$search[5]);
        }else{
            $date_time = $this->prDates();
        }

        $count = count($date_time);
        if($search[5]==''){//默认年月日
            $start = $date_time[0];
            $end = $date_time[count($date_time)-1];
            $whereMap['u.user_register_time'] = array('between',array($start,$end));
        }else{//证明按了点击按钮
            $whereMap = $this->dateArrayUser($search,$count,$date_time);
        }

        $register = $UserModel->userNumTotal($search,1,$whereMap);//总的注册用户

        $where['u.user_attestation'] =2;
        $Authentication = $UserModel->userNumTotal($search,$where,$whereMap);//认证用户数量
         foreach ($date_time as $key=>$vo){
                 $result[] = $vo;
             if($search[5]==1){
                 $whereHe1['u.user_register_time'] = array('EQ',$vo);
             }else if($search[5]==2){
                 $whereHe1['u.user_month'] = array('EQ',$vo);
             }else if($search[5]==3){
                 $whereHe1['u.user_year'] = array('EQ',$vo);
             }else{
                 $whereHe1['u.user_register_time'] = array('EQ',$vo);
             }
             $value= $UserModel->userNumTotal($search,1,$whereHe1);
             $res[] = $value?$value:0;
         }

        if($register!=0){
            $diff = number_format(($Authentication/$register),2)*100;
        }else{
            $diff = 0;

        }
        return json(
            array(
            'time'=>$result,
            'value'=>$res,
            'register'=>$register,
            'Authentication'=>$Authentication,
            'diff'=>$diff
        ));
    }

    /***
     * @return mixed
     * 流失人员情况页面
     */
    public function loss(){
        $AreaModel = new AreaModel();
        $search = input('post.search/a');
        $page = input('post.page');
        $search = $this->search($search, $page);
        $action = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $wherePro['level'] = 1;
        if($search[4]!=''){
            $whereCity['pid'] = $search[4];
        }else{
            $whereCity['pid'] = 2;
        }
        if($search[5]!=''){
            $whereDistrict['pid'] = $search[5];
        }else{
            $whereDistrict['pid'] = 52;
        }
        $province =$AreaModel->selectArea($wherePro);
        $city =$AreaModel->selectArea($whereCity);
        $district =$AreaModel->selectArea($whereDistrict);
        $this->assign(
            array(
                'action'=>$action,
                'page'=>$page,
                'search' => $search,
                'province' => $province,
                'city' => $city,
                'district' => $district,
            )
        );
        return $this->fetch();
    }


    public function lossEcharts(){
        $UserModel = new UserModel();
        $search = input('post.search/a');
        if($search[3]!=''&&$search[4]!=''){
            $date_time = $this->prUserDate($search[3],$search[4],$search[5]);
        }else{
            $date_time = $this->prUserDate();
        }
        $count = count($date_time);
        if($search[5]==''){//默认年月日
            $start = $date_time[0];
            $end = $date_time[count($date_time)-1];
            $whereMap['u.user_register_time'] = array('between',array($start,$end));
        }else{//证明按了点击按钮
            $whereMap = $this->dateArrayUser($search,$count,$date_time);
        }
        $user = $UserModel->userNum($search,$whereMap);
        foreach ($date_time as $key=>$vo){
            $before = date('Y-m-d',(strtotime($vo)-(86400*15)));//十五天前
            $beforeS = date('Y-m-d',(strtotime($vo)-(86400*60)));//60天前
            $whereB['u.user_login_time'] = array('EGT',$before);
            $whereS['u.user_login_time'] = array('ELT',$beforeS);
            $data1 = $UserModel->userNum($search,$whereB);//活跃用户
            $data3 = $UserModel->userNum($search,$whereS);//流失用户
            if($user!=0){
                $data2 = round(($data3/$user),2);//流失用户占比
            }else{
                $data2 = $data3;
            }
            $result['data1'][] =$data1;
            $result['data3'][] =$data3;
            $result['data2'][] =$data2;
            $result['time'][] = $vo;
        }
//        $nowTime = date('Y-m-d',time());
//        $before = date('Y-m-d',(strtotime($nowTime)-(86400*15)));//十五天前
//        $beforeS = date('Y-m-d',(strtotime($nowTime)-(86400*60)));//60天前
//        $whereB['u.user_login_time'] = array('EGT',$before);
//        $whereS['u.user_login_time'] = array('ELT',$beforeS);
//        $whereM['u.user_login_time'] = array('between',array($beforeS,$before));
//
//        $data1 = $UserModel->userNum($search,$whereB);//活跃用户
//        $data2 = $UserModel->userNum($search,$whereS);//不活跃用户
//        $data3 = $UserModel->userNum($search,$whereM);//流失用户
//        $data[0] =$data1;
//        $data[1] =$data2;
//        $data[2] =$data3;
//        $res[0]='活跃用户';
//        $res[1]='不活跃用户';
//        $res[2]='流失用户';

        return json(array('data'=>$result));
    }
}